/***
 *
 * Copyright 2014 Andrew Hall
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package org.statefulj.persistence.mongo;

import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
import org.springframework.data.mongodb.core.mapping.event.AfterDeleteEvent;
import org.springframework.data.mongodb.core.mapping.event.MongoMappingEvent;

import com.mongodb.DBObject;

class MongoCascadeSupport<T> extends AbstractMongoEventListener<Object> {

	private MongoPersister<T> persister;

	public MongoCascadeSupport(MongoPersister<T> persister) {
		this.persister = persister;
	}

	/**
	 * Pass the Save event to the MongoPersister to cascade to the StateDocument
	 *
	 * (non-Javadoc)
	 * @see org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener#onBeforeConvert(java.lang.Object)
	 */
	@Override
	public void onAfterSave(Object source, DBObject dbo) {
		this.persister.onAfterSave(source, dbo);
	}

	@Override
	public void onApplicationEvent(MongoMappingEvent<?> event) {
		super.onApplicationEvent(event);
		if (event.getSource() != null) {
			if (event instanceof AfterDeleteEvent) {
				this.persister.onAfterDelete(((AfterDeleteEvent<?>) event).getType(), event.getDBObject());
			}
		}
	}
}
